package com.ezbuy.common.factory;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * 服务管理类
 *
 * @author Yutianran
 */
public class ServiceFactory {

    //服务类 -> 实现类
    private static Map<Class<?>, Class<?>> router = new HashMap<>();

    //服务类 -> 实现对象的弱引用,GC会回收对象
    private static Map<Class<?>, WeakReference<Object>> implMap = new HashMap<>();

    //在这里静态注册所有服务
    static {
//        router.put(CartService.class, CartServiceRxImpl.class);
//        router.put(ErrorConsumer.class, ErrorConsumerImpl.class);
    }

    //在这里动态注册服务,不直接注册实现类的对象,是为了懒加载,在需要时再创建
    public static void registerService(Class<?> service, Class<?> impl) {
        System.out.println("registerService:"+service.getName());
        router.put(service, impl);
    }

    //反注册服务
    public static void unRegisterService(Class<?> service) {
        System.out.println("unRegisterService:"+service.getName());
        router.remove(service);
    }

    public static <T> T getService(Class<T> serverClass) {
        WeakReference<Object> reference = implMap.get(serverClass);
        Object obj = null;
        //缓存没有被清除掉
        if (reference != null) {
            obj = reference.get();
            if(obj!=null){
                return (T) obj;
            }
        }
        //缓存被清除掉了,或者是还没有创建缓存
        try {
            if (obj == null) {
                Class<?> implClass = router.get(serverClass);
                obj = implClass.newInstance();
                implMap.put(serverClass, new WeakReference<>(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) obj;
    }

}
